package hongcaosp.app.android.user;

import android.content.Intent;
import android.os.Build;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.ArrayList;
import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.common.RGFragmentPagerAdapter;
import hongcaosp.app.android.contact.friends.FindFriendActivity;
import hongcaosp.app.android.login.UserToken;
import hongcaosp.app.android.modle.bean.IUserDetail;
import hongcaosp.app.android.modle.bean.UserInfo;
import hongcaosp.app.android.user.dynamic.DynamicFragment;
import hongcaosp.app.android.user.collect.GridVideoFragment;
import hongcaosp.app.android.user.member.MemberActivity;
import hongcaosp.app.android.user.qrcode.MineQRCodeActivity;
import hongcaosp.app.android.user.settings.SettingsActivity;
import xlj.lib.android.base.component.BaseFragment;
import xlj.lib.android.base.utils.DensityUtils;
import xlj.lib.android.base.utils.StatusBarUtil;
import xlj.lib.android.base.view.NoScrollViewPager;
import xlj.lib.android.base.view.RoundViewOutlineProvider;
import xlj.lib.android.base.view.tablayout.CommonTabLayout;
import xlj.lib.android.base.view.tablayout.listener.CustomTabEntity;
import xlj.lib.android.base.view.tablayout.listener.OnTabSelectListener;

public class UserFragment extends BaseFragment implements IUserDetailView,UserToken.UserChangeListener {
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private NoScrollViewPager viewPager;
    private CommonTabLayout tabLayout;

    private UserDetailPresenter userInfoPresenter;

    private TextView userNameTV, userNameCenterTV, followTxt, sexAgeTxt, cityTxt, schoolTxt, oneDesTxt;
    private ImageView userLogoIV, sexIV,bgIV;
    private List<BaseFragment> childFragments = new ArrayList<>();
    private List<FreshInterface> freshInterfaces = new ArrayList<>();
    private static final String[] TAB_NAME = new String[]{"作品", "动态", "喜欢"};
    private TabEntity workTab,dynamicTab,loveTab;

    @Override
    public void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        View titleView = findViewById(R.id.title_layout);
        bgIV = findViewById(R.id.uc_zoomiv);
        findViewById(R.id.friend_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FindFriendActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.qrcode_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MineQRCodeActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.member_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MemberActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.menu_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SettingsActivity.class);
                startActivity(intent);
            }
        });

        userNameTV = findViewById(R.id.title_uc_title);
        userNameCenterTV = findViewById(R.id.user_name);
        followTxt = findViewById(R.id.follow_fans_like_txt);
        sexAgeTxt = findViewById(R.id.sex_age_txt);
        cityTxt = findViewById(R.id.city_txt);
        schoolTxt = findViewById(R.id.school_txt);
        oneDesTxt = findViewById(R.id.one_des);
        sexIV = findViewById(R.id.sex_iv);

        userLogoIV = findViewById(R.id.user_logo);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            userLogoIV.setOutlineProvider(new RoundViewOutlineProvider(DensityUtils.dip2px(getContext(),8)));
            userLogoIV.setClipToOutline(true);
        }

        userInfoPresenter = new UserDetailPresenter(this);
        if (UserToken.getDefault().getUser() != null) {
            userInfoPresenter.setUserId(UserToken.getDefault().getUser().getUserId());
            userInfoPresenter.getUserInfo();
        }

        findViewById(R.id.title_layout).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        toolbar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        initStatus(toolbar, titleView);
        AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
        View titleCenterLayout = findViewById(R.id.title_center_layout);
        initAppbar(appBarLayout, titleCenterLayout);
        initTabs();

        resetUserPager();
        UserToken.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UserToken.getDefault().unregister(this);
    }

    private void initTabs() {
        tabLayout = findViewById(R.id.uc_tablayout);

        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position, true);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    private void initAppbar(AppBarLayout appBarLayout, final View titleCenterLayout) {
        final View tabLine = findViewById(R.id.tab_line);
        final float height = ((CollapsingToolbarLayout.LayoutParams) tabLine.getLayoutParams()).bottomMargin;
        viewPager = findViewById(R.id.uc_viewpager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(final AppBarLayout appBarLayout, final int verticalOffset) {
                appBarLayout.post(new Runnable() {
                    @Override
                    public void run() {

                        float percent = Float.valueOf(Math.abs(verticalOffset)) / Float.valueOf(appBarLayout.getTotalScrollRange());
                        if (percent != 0 && percent != 1) {
                            viewPager.setNoScroll(true);
                        } else {
                            viewPager.setNoScroll(false);
                        }
                        if (titleCenterLayout != null) {
                            titleCenterLayout.setAlpha(percent);
                        }
                        CollapsingToolbarLayout.LayoutParams lp = (CollapsingToolbarLayout.LayoutParams) tabLine.getLayoutParams();
                        lp.bottomMargin = (int) (height * (1 - percent));
                        tabLine.setLayoutParams(lp);
                    }
                });

            }

        });

        AppBarLayoutOverScrollViewBehavior myAppBarLayoutBehavoir = (AppBarLayoutOverScrollViewBehavior)
                ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).getBehavior();
        myAppBarLayoutBehavoir.setOnProgressChangeListener(new AppBarLayoutOverScrollViewBehavior.onProgressChangeListener() {
            @Override
            public void onProgressChange(float progress, boolean isRelease) {

            }
        });
    }

    private void resetUserPager() {
        setTabData(UserToken.getDefault().getUser());
        if (UserToken.getDefault().getUser() == null) {
            return;
        }
        List<BaseFragment> fragments = new ArrayList<>();
        GridVideoFragment product = new GridVideoFragment();
        product.setType(1);
        product.setUserId(UserToken.getDefault().getUser().getUserId());
        product.setTotalCallBack(new TotalCallBack() {
            @Override
            public void onTotalSend(int total) {
                if (workTab != null) {
                    workTab.title = total + "";
                }
                tabLayout.notifyDataSetChanged();
            }
        });

        GridVideoFragment liked = new GridVideoFragment();
        liked.setType(2);
        liked.setUserId(UserToken.getDefault().getUser().getUserId());
        liked.setTotalCallBack(new TotalCallBack() {
            @Override
            public void onTotalSend(int total) {
                if (loveTab != null) {
                    loveTab.title = total + "";
                }
                tabLayout.notifyDataSetChanged();
            }
        });

        DynamicFragment dynamicFragment = new DynamicFragment();
        dynamicFragment.setUserId(UserToken.getDefault().getUser().getUserId());
        dynamicFragment.setTotalCallBack(new TotalCallBack() {
            @Override
            public void onTotalSend(int total) {
                if (dynamicTab != null) {
                    dynamicTab.title = total + "";
                }
                tabLayout.notifyDataSetChanged();
            }
        });

        fragments.add(product);
        fragments.add(dynamicFragment);
        fragments.add(liked);

        childFragments = fragments;

        freshInterfaces.add(product);
        freshInterfaces.add(dynamicFragment);
        freshInterfaces.add(liked);

        RGFragmentPagerAdapter RGFragmentPagerAdapter = new RGFragmentPagerAdapter(getChildFragmentManager(), fragments, TAB_NAME);
        viewPager.setAdapter(RGFragmentPagerAdapter);

    }

    /**
     * 假数据
     *
     * @return
     */
    private void setTabData(IUserDetail userDetail) {
        mTabEntities.clear();
        if (userDetail == null) return;
        workTab = new TabEntity( userDetail.worksCount() + "",TAB_NAME[0]);
        dynamicTab = new TabEntity(userDetail.dynamicCount() + "",TAB_NAME[1]);
        loveTab = new TabEntity(userDetail.getLikeVideoCount() + "",TAB_NAME[2]);
        mTabEntities.add(workTab);
        mTabEntities.add(dynamicTab);
        mTabEntities.add(loveTab);

        tabLayout.setTabData(mTabEntities);
    }

    private void initStatus(Toolbar toolbar, View titleView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4以下不支持状态栏变色
            //注意了，这里使用了第三方库 StatusBarUtil，目的是改变状态栏的alpha
            //这里是重设我们的title布局的topMargin，StatusBarUtil提供了重设的方法，但是我们这里有两个布局
            //TODO 关于为什么不把Toolbar和@layout/layout_uc_head_title放到一起，是因为需要Toolbar来占位，防止AppBarLayout折叠时将title顶出视野范围
            int statusBarHeight = StatusBarUtil.getStatusBarHeight(getActivity());
            CollapsingToolbarLayout.LayoutParams lp1 = (CollapsingToolbarLayout.LayoutParams) titleView.getLayoutParams();
            lp1.topMargin = statusBarHeight;
            titleView.setLayoutParams(lp1);
            CollapsingToolbarLayout.LayoutParams lp2 = (CollapsingToolbarLayout.LayoutParams) toolbar.getLayoutParams();
            lp2.height = lp2.height + statusBarHeight;
            toolbar.setLayoutParams(lp2);
        }
    }

    @Override
    public int getLayoutRes() {
        return R.layout.fragment_user;
    }

    @Override
    public void updateUserData(IUserDetail user) {

        userNameTV.setText(user.getUserName());
        userNameCenterTV.setText(user.getUserName());
        Glide.with(this).load(user.getUserLogo()).centerCrop().diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(R.drawable.icon_user_head).into(userLogoIV);
        Glide.with(this).load(user.getUserLogo()).diskCacheStrategy(DiskCacheStrategy.SOURCE).centerCrop().into(bgIV);
        followTxt.setText(user.getFollowCount() + "关注   " + user.getFansCount() + "粉丝   " + user.getLikeCount() + "获赞");
        if (user.getSex() == 1) {
            sexIV.setImageResource(R.drawable.icon_sex_boy);
        } else if (user.getSex() == 2){
            sexIV.setImageResource(R.drawable.icon_sex_girl);
        } else {
            sexIV.setImageDrawable(null);
        }
        setTabData(user);
        sexAgeTxt.setText(user.getAge() + "岁");
        cityTxt.setText(user.getCity());
        schoolTxt.setText(user.getSchool());
        oneDesTxt.setText(user.getUserComment());
        for (FreshInterface freshInterface : freshInterfaces) {
            freshInterface.fresh();
        }
    }

    @Override
    public void onHide() {
        super.onHide();
        if (viewPager == null) return;
        int position = viewPager.getCurrentItem();
        if (position >= 0 && position < childFragments.size()) {
            childFragments.get(position).onHide();
        }
    }

    @Override
    public void onShow() {
        super.onShow();
        if (viewPager == null) return;
        int position = viewPager.getCurrentItem();
        if (position >= 0 && position < childFragments.size()) {
            childFragments.get(position).onShow();
        }
        if (userInfoPresenter != null && UserToken.getDefault().getUser() != null) {
            userInfoPresenter.setUserId(UserToken.getDefault().getUser().getUserId());
            userInfoPresenter.getUserInfo();
        }
    }

    @Override
    public void onUserChange(UserInfo user) {
        resetUserPager();
    }
}
